﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Xml;
using com.lover.astd.common.model;
using com.lover.astd.common.model.battle;

namespace com.lover.astd.common.logic
{
    public class CampaignMgr : MgrBase
    {
        public CampaignMgr() { _logColor = System.Drawing.Color.DeepSkyBlue; }
        public List<CampaignItem> getCampaigns(ProtocolMgr protocol, ILogger logger)
        {
            List<CampaignItem> campaigns = new List<CampaignItem>();
            string url = "/root/campaign!getCampaignList.action";
            com.lover.astd.common.model.ServerResult result = protocol.getXml(url, "获取单人战役信息");
            if (result == null) return null;
            if (!result.CmdSucceed) return null;
            XmlDocument xml = result.CmdResult;
            // 有卡就用
            tryUseCard(protocol, logger, xml);
            XmlNodeList nodes = xml.SelectNodes("/results/campaignnew");
            foreach (XmlNode node in nodes)
            {
                XmlNodeList childs = node.ChildNodes;
                CampaignItem item = new CampaignItem();
                foreach (XmlNode child in childs)
                {
                    if (child.Name == "id") item.id = Int32.Parse(child.InnerText);
                    else if (child.Name == "name") item.name = child.InnerText;
                    else if (child.Name == "armynum") item.armynum = Int32.Parse(child.InnerText);
                    else if (child.Name == "times") item.times = Int32.Parse(child.InnerText);
                    else if (child.Name == "remain6num") item.remain6num = Int32.Parse(child.InnerText);
                }
                if (item.times >= 100) continue;
                campaigns.Add(item);
            }
            return campaigns;
        }
        /// <summary>
        /// 0=打完返回, 1=http error, 2=, 3=军令已经CD, 4=没有令了, 5=征兵失败, 6=战役未完成,实力不够,
        /// 7=获取战役奖励失败, 10=战役已打完
        /// </summary>
        /// <param name="protocol"></param>
        /// <param name="logger"></param>
        /// <param name="campaign_id_from">从哪个id开始</param>
        /// <param name="count">打多少次</param>
        public int startCampaign(ProtocolMgr protocol, ILogger logger, CampaignItem item)
        {
            if (item == null)
            {
                logInfo(logger, "战役已打完");
                return 10;
            }
            int completed = 0;
            int start_ok = innerStartCampaign(protocol, logger, item.id, item.name);
            if (start_ok == 1) return 1; // http error, 继续下次
            else if (start_ok == 2) // 正在战役中, 不用处理, 直接完成战役就好
            {
                string reward_now = getCampaignInfo(protocol, logger, out completed);
                if (completed > 0)
                {
                    bool got_result_now = false;
                    if (item.remain6num > 0) got_result_now = getCampaignReward(protocol, logger, 2);
                    else got_result_now = getCampaignReward(protocol, logger, 0);
                    if (!got_result_now) { logInfo(logger, "获取战役奖励失败, 停止战役"); return 7; }
                    logInfo(logger, String.Format("获取战役奖励: {0}", reward_now));
                    item.times++;
                    return 0;
                }
            } 
            else if (start_ok == 3) { logInfo(logger, "军令已经CD"); return 3; }
            else if (start_ok == 4) { logInfo(logger, "没有令了"); return 4; }
            else if (start_ok == 5) { logInfo(logger, "征兵失败"); return 5; }

            bool complete_ok = completeCampaign(protocol, logger);
            if (!complete_ok) { logInfo(logger, "战役未完成, 请检查是否你的实力不足以一半兵力完成此战役"); return 6; }
            string reward = getCampaignInfo(protocol, logger, out completed);
            if (completed == 0) { logInfo(logger, "战役未完成, 请检查是否你的实力不足以一半兵力完成此战役"); return 6; }
            bool got_result = false;
            if (item.remain6num > 0) got_result = getCampaignReward(protocol, logger, 2);
            else got_result = getCampaignReward(protocol, logger, 0);
            if (!got_result) { logInfo(logger, "获取战役奖励失败, 停止战役"); return 7; }
            logInfo(logger, String.Format("获取战役奖励: {0}", reward));
            item.times++;
            
            return 0;
        }
        /// <summary>
        /// return 0=ok, 1=http error, 2=in campaign, 3=battle cd, 4=no order, 5=征兵失败, 6=unknown
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        private int innerStartCampaign(ProtocolMgr protocol, ILogger logger, int id, string name)
        {
            int force_result = ServiceFactory.getTroopManager().makeSureForce(protocol, logger);
            if (force_result > 0) // 保证兵力失败, 停止
            {
                logInfo(logger, "征兵失败, 停止战役");
                return 5;
            }
            
            string url = "/root/campaign!startWar.action";
            string data = "campaignId=" + id;
            string desc = String.Format("开始战役[{0}]", name);
            com.lover.astd.common.model.ServerResult result = protocol.postXml(url, data, desc);
            if (result == null) return 1;
            if (!result.CmdSucceed)
            {
                string cmderror = result.CmdError;
                if (cmderror.Contains("正在战役中") || cmderror.Contains("正在戰役中")) return 2;
                else if (cmderror.Contains("还没有冷却") || cmderror.Contains("還沒有冷卻")) return 3;
                else if (cmderror.Contains("没有可用的军令") || cmderror.Contains("沒有可用的軍令")) return 4;
                else return 5;
            }
            logger.log(desc, _logColor);
            return 0;
        }
        private bool completeCampaign(ProtocolMgr protocol, ILogger logger)
        {
            string url = "/root/campaign!attackAll.action";
            com.lover.astd.common.model.ServerResult result = protocol.getXml(url, "自动战役");
            if (result == null || !result.CmdSucceed) return false;
            return true;
        }
        private string getCampaignInfo(ProtocolMgr protocol, ILogger logger, out int completed)
        {
            completed = 0;
            string url = "/root/campaign!getCampaignNewInfo.action";
            com.lover.astd.common.model.ServerResult result = protocol.getXml(url, "获取战役信息");
            if (result == null || !result.CmdSucceed) return "";
            XmlDocument xml = result.CmdResult;

            XmlNode finish_node = xml.SelectSingleNode("/results/finish");
            if (finish_node != null && finish_node.InnerText.Equals("0")) { return ""; }
            
            completed = 1;
            int gem_count = 0, jungong_count = 0, tf_count = 0, cooper_count = 0, stone_count = 0;

            XmlNode finish_reward = xml.SelectSingleNode("/results/finishreward");
            foreach (XmlNode node in finish_reward.ChildNodes)
            {
                if (node.Name == "copper") cooper_count += Int32.Parse(node.InnerText);
                else if (node.Name == "baoshi") gem_count += Int32.Parse(node.InnerText);
                else if (node.Name == "bowlder") stone_count += Int32.Parse(node.InnerText);
                else if (node.Name == "tf") tf_count += Int32.Parse(node.InnerText);
                else if (node.Name == "jungong") jungong_count += Int32.Parse(node.InnerText);
            }
            XmlNode reward = xml.SelectSingleNode("/results/reward");
            foreach (XmlNode node in reward.ChildNodes)
            {
                if (node.Name == "copper") cooper_count += Int32.Parse(node.InnerText);
                else if (node.Name == "baoshi") gem_count += Int32.Parse(node.InnerText);
                else if (node.Name == "bowlder") stone_count += Int32.Parse(node.InnerText);
                else if (node.Name == "tf") tf_count += Int32.Parse(node.InnerText);
                else if (node.Name == "jungong") jungong_count += Int32.Parse(node.InnerText);
            }
            //XmlNode pre_reward = xml.SelectSingleNode("/results/prereward");
            //foreach (XmlNode node in pre_reward.ChildNodes)
            //{
            //    if (node.Name == "copper") cooper_count += Int32.Parse(node.InnerText);
            //    else if (node.Name == "baoshi") gem_count += Int32.Parse(node.InnerText);
            //    else if (node.Name == "bowlder") stone_count += Int32.Parse(node.InnerText);
            //    else if (node.Name == "tf") tf_count += Int32.Parse(node.InnerText);
            //    else if (node.Name == "jungong") jungong_count += Int32.Parse(node.InnerText);
            //}
            string desc = String.Format("银币+{0}, 玉石+{1}, 军工+{2}, 突飞令+{3}, 宝石+{4}",
                cooper_count, stone_count, jungong_count, tf_count, gem_count);
            return desc;
        }
        private bool getCampaignReward(ProtocolMgr protocol, ILogger logger, int mode)
        {
            string url = "/root/campaign!getCampaignNewReward.action";
            string data = "mode=" + mode;
            com.lover.astd.common.model.ServerResult result = protocol.postXml(url, data, "获取战役奖励");
            if (result == null || !result.CmdSucceed) return false;
            //<results><state>1</state><message></message></results>
            return true;
        }
    }
}
